package xin.alum.aim;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.util.AttributeKey;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import xin.alum.aim.constant.ChannelPlatform;
import xin.alum.aim.groups.Sessions;
import xin.alum.aim.handler.AimReceiver;
import xin.alum.aim.model.Reply;
import xin.alum.aim.model.Sent;
import xin.alum.aim.model.proto.Packet;

/**
 * @auther Alum(alum @ live.cn)
 * @date 2021/8/7 9:53 1231321
 */
@Component
public class AimReciveService extends AimReceiver {

    @Override
    public boolean onHandShake(Channel ch, FullHttpRequest req, FullHttpResponse res) {
        String tokens = (String) sessions.getAttr(ch, "token");
        res.setStatus(HttpResponseStatus.UNAUTHORIZED);
        return tokens != null;
    }

    /**
     * @param ch
     */
    @Override
    public void onHandShaked(Channel ch) {
        String token = ch.attr(AttributeKey.valueOf("token")).toString();
        sessions.bindUser(ch, token, ChannelPlatform.WINDOWS, "");
    }

    String groupKey = "test_group";

    @SneakyThrows
    @Override
    public void onRecive(Channel ch, Sent s) {
        StopWatch stopWatch = new StopWatch();
        Sessions sessions = groups.get(groupKey);
        if (!sessions.contains(ch)) {
            sessions = groups.bind(ch, groupKey);
        }
        Packet.Data d = (Packet.Data) s.unpack(Packet.Data.class);
        Reply reply = new Reply(s.getKey());
        Packet.Data.Builder b = Packet.Data.newBuilder();
        b.putAllAttrs(d.getAttrsMap());
        b.putAttrs("success", "处理成功");
        reply.setData(b.build());
//        if (reply.getTimestamp() % 5000 == 0)
//            logger.info("{}群发【{}】消息{}人", ch, sessions.name(), sessions.size());
        groups.sends(groupKey, reply);
        if (stopWatch.getTotalTimeMillis() > 100) {
            logger.warn("{}群发消息-{},{}人,用时-{}", ch, s.getKey(), sessions.size(), stopWatch.getLastTaskTimeMillis());
        }
    }
}
